package com.munhrasoft.dinamica.business.logic;

import java.util.List;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.munhrasoft.dinamica.business.entities.Cliente;
import com.munhrasoft.dinamica.business.entities.Imovel;

@Stateless
public class ClienteEJB {

	private static Logger logger = Logger.getLogger(ClienteEJB.class.getName());
	
	@PersistenceContext(unitName = "dinamicaPU")
	private EntityManager em;

	/*
	 * Only for test
	 */
	/*
	 * public List<Cliente> findClientes(){ TypedQuery<Cliente> query =
	 * em.createNamedQuery("findAllClientes", Cliente.class); return
	 * query.getResultList(); }
	 */

	@SuppressWarnings("unchecked")
	public List<Cliente> findClientesByName(String name) {
		Query query = em.createNamedQuery("findByProponente");
		query.setParameter("name", name.toLowerCase() + "%");
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Cliente> fetchAllClientes() {
		Query query = em.createNamedQuery("findAllClientes");
		return query.getResultList();
	}

	public Imovel imovelPorMatricula(String matricula) {
		
		Query query = em.createNamedQuery("findImovelByMatricula");
		query.setParameter("mat", matricula);
		if (query.getResultList().isEmpty()) {
			logger.info("ImovelPorMatricula  nao encontrou !");
			return null;
		} else {
			logger.info("Imoveis do cliente matricula encontrada "+((Imovel) query.getResultList().get(0)).getMatricula());
			return (Imovel) query.getResultList().get(0);
		}

	}

	public Cliente createCliente(Cliente cliente) {
		em.persist(cliente);
		return cliente;
	}

	public Cliente updateCliente(Cliente cliente) {
		return em.merge(cliente);
	}

	public void removeCliente(Cliente cliente) {
		em.remove(em.merge(cliente));
	}

}
